package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;


    /**
     * 保存菜品和口味
     * @param dishDTO
     */
    @Transactional
    public void saveDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        // 对象属性拷贝,将dishDTO中的属性拷贝到dish中,前提是两个对象中的属性名相同，第一个参数是源，第二个参数是目标
        BeanUtils.copyProperties(dishDTO, dish);
        // 保存一条菜品
        dishMapper.insert(dish);
        // 獲取insert生成的主鍵值
        Long dishId = dish.getId();
        // 保存n个口味
        List<DishFlavor> flavorIds = dishDTO.getFlavors();
        if (flavorIds != null && flavorIds.size() > 0) {
            flavorIds.forEach(flavorId -> {
                flavorId.setDishId(dishId);
            });
            flavorMapper.insertBatch (flavorIds);
        }
    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult getDishList(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.selectDishList(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 批量删除指定菜品
     * @param ids
     */
    @Transactional
    public void deleteDish(List<Long> ids) {
        // 当前菜品是否在售
        for(Long id : ids){
            Dish dish = dishMapper.selectById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 是否被套餐关联
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishId(ids);
        if (setMealIds != null && setMealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品数据
        for (Long id : ids) {
            dishMapper.deleteDish(id);
            // 删除口味数据
            flavorMapper.deleteByDishId(id);
        }
    }


    /**
     * 查询指定菜品
     * @param id
     * @return
     */
    public DishVO selectById(Long id) {
        log.info("查询指定菜品：{}", id);
        // 根据ID查询菜品数据
        Dish dish = dishMapper.selectDetailById(id);
        // 根据ID查询口味数据
        List<DishFlavor> dishFlavor = flavorMapper.selectFlavorByDishId(id);
        // 将数据封装到VO中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    /**
     * 更新菜品
     * @param dishDTO
     */
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        // 更新菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);
        // 更新口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 先删除原有的口味数据
            flavorMapper.deleteByDishId(dishDTO.getId());
            // 再插入新的口味数据
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });
            flavorMapper.insertBatch(flavors);
        }
    }

    public List<DishVO> getDishByCategoriesId(Dish dish) {
        List<Dish> dishList = dishMapper.getDishByCategoriesId(dish.getStatus() , dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.selectFlavorByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    /**
     * 根据菜品ID修改菜品状态
     * @param status
     * @param id
     */
    public void setStatus(Integer status, Long id) {
        //根据ID查询菜品，并设置状态
        dishMapper.setStatus(status,id);
    }
}
